<template>
  <div
    class="floating-button"
    ref="button"
    :style="{ top: position.top + 'px', left: position.left + 'px' }"
    @mousedown="startDrag"
    @touchstart="startDrag"
    @click="handleClick"
  >
    <slot></slot>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";

const button = ref(null);
const position = reactive({ top: window.innerHeight - 100, left: window.innerWidth - 100 });
let offset = { x: 0, y: 0 };
let isDragging = false;

const startDrag = event => {
  event.preventDefault(); // 防止默认的拖动行为
  isDragging = true;
  const boundingRect = button.value.getBoundingClientRect();
  offset = {
    x: event.clientX - boundingRect.left,
    y: event.clientY - boundingRect.top
  };

  document.addEventListener("mousemove", handleDrag);
  document.addEventListener("mouseup", stopDrag);

  document.addEventListener("touchmove", handleDrag);
  document.addEventListener("touchend", stopDrag);

  return false; // 取消默认行为
};

const handleDrag = event => {
  if (isDragging) {
    event.preventDefault();
    position.left = event.clientX - offset.x;
    position.top = event.clientY - offset.y;
  }
};

const stopDrag = () => {
  isDragging = false;

  document.removeEventListener("mousemove", handleDrag);
  document.removeEventListener("mouseup", stopDrag);

  document.removeEventListener("touchmove", handleDrag);
  document.removeEventListener("touchend", stopDrag);
};
const emit = defineEmits(["click"]);

const handleClick = event => {
  event.preventDefault();
  emit("click");
};
</script>

<style scoped>
.floating-button {
  position: fixed;
  width: 50px;
  height: 50px;
  background-color: #007bff;
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 9999;
}
</style>
